home *** CD-ROM | disk | FTP | other *** search
Wrap
# Source Generated with Decompyle++ # File: in.pyo (Python 2.5) __author__ = "Patrick K. O'Brien <pobrien@orbtech.com>" __cvsid__ = '$Id: shell.py 46528 2007-06-18 19:09:00Z RD $' __revision__ = '$Revision: 46528 $'[11:-2] import wx from wx import stc import keyword import os import sys import time from buffer import Buffer import dispatcher import editwindow import frame from pseudo import PseudoFileIn from pseudo import PseudoFileOut from pseudo import PseudoFileErr from version import VERSION sys.ps3 = '<-- ' NAVKEYS = (wx.WXK_END, wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN, wx.WXK_PRIOR, wx.WXK_NEXT) class ShellFrame(frame.Frame, frame.ShellFrameMixin): name = 'Shell Frame' revision = __revision__ def __init__(self, parent = None, id = -1, title = 'PyShell', pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, locals = None, InterpClass = None, config = None, dataDir = None, *args, **kwds): frame.Frame.__init__(self, parent, id, title, pos, size, style) frame.ShellFrameMixin.__init__(self, config, dataDir) if size == wx.DefaultSize: self.SetSize((750, 525)) intro = 'PyShell %s - The Flakiest Python Shell' % VERSION self.SetStatusText(intro.replace('\n', ', ')) self.shell = Shell(parent = self, id = -1, introText = intro, locals = locals, InterpClass = InterpClass, startupScript = self.startupScript, execStartupScript = self.execStartupScript, *args, **kwds) self.shell.setStatusText = self.SetStatusText self.shell.SetFocus() self.LoadSettings() def OnClose(self, event): if self.shell.waiting: if event.CanVeto(): event.Veto(True) else: self.SaveSettings() self.shell.destroy() self.Destroy() def OnAbout(self, event): title = 'About PyShell' text = 'PyShell %s\n\n' % VERSION + 'Yet another Python shell, only flakier.\n\n' + "Half-baked by Patrick K. O'Brien,\n" + 'the other half is still in the oven.\n\n' + 'Shell Revision: %s\n' % self.shell.revision + 'Interpreter Revision: %s\n\n' % self.shell.interp.revision + 'Platform: %s\n' % sys.platform + 'Python Version: %s\n' % sys.version.split()[0] + 'wxPython Version: %s\n' % wx.VERSION_STRING + '\t(%s)\n' % ', '.join(wx.PlatformInfo[1:]) dialog = wx.MessageDialog(self, text, title, wx.OK | wx.ICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnHelp(self, event): frame.ShellFrameMixin.OnHelp(self, event) def LoadSettings(self): if self.config is not None: frame.ShellFrameMixin.LoadSettings(self) frame.Frame.LoadSettings(self, self.config) self.shell.LoadSettings(self.config) def SaveSettings(self, force = False): if self.config is not None: frame.ShellFrameMixin.SaveSettings(self) if self.autoSaveSettings or force: frame.Frame.SaveSettings(self, self.config) self.shell.SaveSettings(self.config) def DoSaveSettings(self): if self.config is not None: self.SaveSettings(force = True) self.config.Flush() HELP_TEXT = '* Key bindings:\nHome Go to the beginning of the command or line.\nShift+Home Select to the beginning of the command or line.\nShift+End Select to the end of the line.\nEnd Go to the end of the line.\nCtrl+C Copy selected text, removing prompts.\nCtrl+Shift+C Copy selected text, retaining prompts.\nAlt+C Copy to the clipboard, including prefixed prompts.\nCtrl+X Cut selected text.\nCtrl+V Paste from clipboard.\nCtrl+Shift+V Paste and run multiple commands from clipboard.\nCtrl+Up Arrow Retrieve Previous History item.\nAlt+P Retrieve Previous History item.\nCtrl+Down Arrow Retrieve Next History item.\nAlt+N Retrieve Next History item.\nShift+Up Arrow Insert Previous History item.\nShift+Down Arrow Insert Next History item.\nF8 Command-completion of History item.\n (Type a few characters of a previous command and press F8.)\nCtrl+Enter Insert new line into multiline command.\nCtrl+] Increase font size.\nCtrl+[ Decrease font size.\nCtrl+= Default font size.\nCtrl-Space Show Auto Completion.\nCtrl-Alt-Space Show Call Tip.\nShift+Enter Complete Text from History.\nCtrl+F Search\nF3 Search next\nCtrl+H "hide" lines containing selection / "unhide"\nF12 on/off "free-edit" mode\n' class ShellFacade: name = 'Shell Interface' revision = __revision__ def __init__(self, other): d = self.__dict__ d['other'] = other d['helpText'] = HELP_TEXT def help(self): self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other, name): return getattr(self.other, name) else: raise AttributeError, name def __setattr__(self, name, value): if self.__dict__.has_key(name): self.__dict__[name] = value elif hasattr(self.other, name): setattr(self.other, name, value) else: raise AttributeError, name def _getAttributeNames(self): list = [ 'about', 'ask', 'autoCallTip', 'autoComplete', 'autoCompleteAutoHide', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', 'callTipInsert', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom'] list.sort() return list class Shell(editwindow.EditWindow): name = 'Shell' revision = __revision__ def __init__(self, parent, id = -1, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.CLIP_CHILDREN, introText = '', locals = None, InterpClass = None, startupScript = None, execStartupScript = True, *args, **kwds): editwindow.EditWindow.__init__(self, parent, id, pos, size, style) self.wrap() if locals is None: import __main__ locals = __main__.__dict__ self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr if InterpClass == None: Interpreter = Interpreter import interpreter else: Interpreter = InterpClass self.reader = PseudoFileIn(self.readline, self.readlines) self.reader.input = '' self.reader.isreading = False self.interp = Interpreter(locals = locals, rawin = self.raw_input, stdin = self.reader, stdout = PseudoFileOut(self.writeOut), stderr = PseudoFileErr(self.writeErr), *args, **kwds) self.buffer = Buffer() self.autoCompleteKeys = self.interp.getAutoCompleteKeys() self.promptPosStart = 0 self.promptPosEnd = 0 self.more = False self.history = [] self.historyIndex = -1 self.noteMode = 0 self.MarkerDefine(0, stc.STC_MARK_ROUNDRECT) self.searchTxt = '' self.Bind(wx.EVT_CHAR, self.OnChar) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu) self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI) self.Bind((wx.EVT_MENU,), (lambda evt: self.Cut()), id = wx.ID_CUT) self.Bind((wx.EVT_MENU,), (lambda evt: self.Copy()), id = wx.ID_COPY) self.Bind((wx.EVT_MENU,), (lambda evt: self.CopyWithPrompts()), id = frame.ID_COPY_PLUS) self.Bind((wx.EVT_MENU,), (lambda evt: self.Paste()), id = wx.ID_PASTE) self.Bind((wx.EVT_MENU,), (lambda evt: self.PasteAndRun()), id = frame.ID_PASTE_PLUS) self.Bind((wx.EVT_MENU,), (lambda evt: self.SelectAll()), id = wx.ID_SELECTALL) self.Bind((wx.EVT_MENU,), (lambda evt: self.Clear()), id = wx.ID_CLEAR) self.Bind((wx.EVT_MENU,), (lambda evt: self.Undo()), id = wx.ID_UNDO) self.Bind((wx.EVT_MENU,), (lambda evt: self.Redo()), id = wx.ID_REDO) self.waiting = False self.Bind(wx.EVT_IDLE, self.OnIdle) self.showIntro(introText) self.setBuiltinKeywords() self.setLocalShell() if execStartupScript: if startupScript is None: startupScript = os.environ.get('PYTHONSTARTUP') self.execStartupScript(startupScript) else: self.prompt() wx.CallAfter(self.ScrollToLine, 0) def clearHistory(self): self.history = [] self.historyIndex = -1 dispatcher.send(signal = 'Shell.clearHistory') def destroy(self): del self.interp def setFocus(self): self.SetFocus() def OnIdle(self, event): if self.waiting: time.sleep(0.05) event.Skip() def showIntro(self, text = ''): if text: self.write(text) try: if self.interp.introText: if text and not text.endswith(os.linesep): self.write(os.linesep) self.write(self.interp.introText) except AttributeError: pass def setBuiltinKeywords(self): import __builtin__ __builtin__.close = __builtin__.exit = __builtin__.quit = 'Click on the close button to leave the application.' def quit(self): self.write('Click on the close button to leave the application.') def setLocalShell(self): self.interp.locals['shell'] = ShellFacade(other = self) def execStartupScript(self, startupScript): if startupScript and os.path.isfile(startupScript): text = 'Startup script executed: ' + startupScript self.push('print %r; execfile(%r)' % (text, startupScript)) self.interp.startupScript = startupScript else: self.push('') def about(self): text = '\nAuthor: %r\nPy Version: %s\nPy Shell Revision: %s\nPy Interpreter Revision: %s\nPython Version: %s\nwxPython Version: %s\nwxPython PlatformInfo: %s\nPlatform: %s' % (__author__, VERSION, self.revision, self.interp.revision, sys.version.split()[0], wx.VERSION_STRING, str(wx.PlatformInfo), sys.platform) self.write(text.strip()) def OnChar(self, event): if self.noteMode: event.Skip() return None if not self.CanEdit(): return None key = event.GetKeyCode() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd if key in [ wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]: pass elif key in self.autoCompleteKeys: if self.AutoCompActive(): self.AutoCompCancel() command = self.GetTextRange(stoppos, currpos) + chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key == ord('('): if self.AutoCompActive(): self.AutoCompCancel() self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) + '(' self.write('(') self.autoCallTipShow(command, self.GetCurrentPos() == self.GetTextLength()) else: event.Skip() def OnKeyDown(self, event): key = event.GetKeyCode() if self.AutoCompActive(): event.Skip() return None controlDown = event.ControlDown() altDown = event.AltDown() shiftDown = event.ShiftDown() currpos = self.GetCurrentPos() endpos = self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd() if controlDown and shiftDown and key in (ord('F'), ord('f')): li = self.GetCurrentLine() m = self.MarkerGet(li) if m & 1: startP = self.PositionFromLine(li) self.MarkerDelete(li, 0) maxli = self.GetLineCount() li += 1 li0 = li while li < maxli and self.GetLineVisible(li) == 0: li += 1 endP = self.GetLineEndPosition(li - 1) self.ShowLines(li0, li - 1) self.SetSelection(startP, endP) return None (startP, endP) = self.GetSelection() endP -= 1 startL = self.LineFromPosition(startP) endL = self.LineFromPosition(endP) if endL == self.LineFromPosition(self.promptPosEnd): endL -= 1 m = self.MarkerGet(startL) self.MarkerAdd(startL, 0) self.HideLines(startL + 1, endL) self.SetCurrentPos(startP) if False and key == wx.WXK_F12: if self.noteMode: self.promptPosEnd = self.PositionFromLine(self.GetLineCount() - 1) + len(str(sys.ps1)) self.GotoLine(self.GetLineCount()) self.GotoPos(self.promptPosEnd) self.prompt() self.SetCaretForeground('black') self.SetCaretWidth(1) self.SetCaretPeriod(500) else: self.SetCaretForeground('red') self.SetCaretWidth(4) self.SetCaretPeriod(0) self.noteMode = not (self.noteMode) return None if self.noteMode: event.Skip() return None if (not controlDown and not shiftDown or not altDown) and key in [ wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]: if self.CallTipActive(): self.CallTipCancel() self.processLine() elif shiftDown and key in [ wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]: self.OnShowCompHistory() elif controlDown and key in [ wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]: if self.CallTipActive(): self.CallTipCancel() if currpos == endpos: self.processLine() else: self.insertLineBreak() elif controlDown and altDown: event.Skip() elif key == wx.WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand() elif key == wx.WXK_BACK and controlDown and shiftDown: self.clearCommand() elif controlDown and key in (ord(']'), wx.WXK_NUMPAD_ADD): dispatcher.send(signal = 'FontIncrease') elif controlDown and key in (ord('['), wx.WXK_NUMPAD_SUBTRACT): dispatcher.send(signal = 'FontDecrease') elif controlDown and key in (ord('='), wx.WXK_NUMPAD_DIVIDE): dispatcher.send(signal = 'FontDefault') elif (controlDown or key in (ord('X'), ord('x')) or shiftDown) and key == wx.WXK_DELETE: self.Cut() elif controlDown and not shiftDown and key in (ord('C'), ord('c'), wx.WXK_INSERT): self.Copy() elif controlDown and shiftDown and key in (ord('C'), ord('c'), wx.WXK_INSERT): self.CopyWithPrompts() elif altDown and not controlDown and key in (ord('C'), ord('c'), wx.WXK_INSERT): self.CopyWithPromptsPrefixed() elif key == wx.WXK_HOME: home = self.promptPosEnd if currpos > home: self.SetCurrentPos(home) if not selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() elif selecting and key not in NAVKEYS and not self.CanEdit(): pass elif (controlDown and not shiftDown or key in (ord('V'), ord('v')) or shiftDown) and not controlDown and key == wx.WXK_INSERT: self.Paste() elif controlDown and key == wx.WXK_SPACE: self.OnCallTipAutoCompleteManually(shiftDown) elif controlDown and shiftDown and key in (ord('V'), ord('v')): self.PasteAndRun() elif (controlDown or key == wx.WXK_UP or altDown) and key in (ord('P'), ord('p')): self.OnHistoryReplace(step = +1) elif (controlDown or key == wx.WXK_DOWN or altDown) and key in (ord('N'), ord('n')): self.OnHistoryReplace(step = -1) elif (shiftDown or key == wx.WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step = +1) elif (shiftDown or key == wx.WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step = -1) elif key == wx.WXK_F8: self.OnHistorySearch() elif key == wx.WXK_BACK: if selecting and self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd: event.Skip() elif key in (wx.WXK_TAB, wx.WXK_DELETE): if self.CanEdit(): event.Skip() elif key == wx.WXK_INSERT: pass elif controlDown and key in (ord('L'), ord('l')): pass elif controlDown and key in (ord('T'), ord('t')): pass elif key in NAVKEYS: event.Skip() elif not self.CanEdit(): pass else: event.Skip() def OnShowCompHistory(self): his = self.history[:] joined = ' '.join(his) import re newlist = re.split('[ \\.\\[\\]=}(\\)\\,0-9"]', joined) thlist = [] for i in newlist: if len(i) > 1: thlist.append(i) continue unlist = _[1] unlist.sort((lambda a, b: cmp(a.lower(), b.lower()))) self.AutoCompSetIgnoreCase(True) stringlist = ' '.join(unlist) cpos = self.GetCurrentPos() - 1 while chr(self.GetCharAt(cpos)).isalnum(): cpos -= 1 continue [] self.AutoCompShow(self.GetCurrentPos() - cpos - 1, stringlist) def clearCommand(self): startpos = self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = False def OnHistoryReplace(self, step): self.clearCommand() self.replaceFromHistory(step) def replaceFromHistory(self, step): ps2 = str(sys.ps2) self.ReplaceSelection('') newindex = self.historyIndex + step if newindex <= newindex: pass elif newindex <= len(self.history): self.historyIndex = newindex if newindex <= newindex: pass elif newindex <= len(self.history) - 1: command = self.history[self.historyIndex] command = command.replace('\n', os.linesep + ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): if not self.CanEdit(): return None startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): if not self.CanEdit(): return None startpos = self.GetCurrentPos() numCharsAfterCursor = self.GetTextLength() - startpos searchText = self.getCommand(rstrip = False) if numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor] if not searchText: return None if self.historyIndex <= -1 or self.historyIndex >= len(self.history) - 2: searchOrder = range(len(self.history)) else: searchOrder = range(self.historyIndex + 1, len(self.history)) + range(self.historyIndex) for i in searchOrder: command = self.history[i] if command[:len(searchText)] == searchText: self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) self.historyIndex = i break continue def setStatusText(self, text): print text def insertLineBreak(self): if self.CanEdit(): self.write(os.linesep) self.more = True self.prompt() def processLine(self): thepos = self.GetCurrentPos() startpos = self.promptPosEnd endpos = self.GetTextLength() ps2 = str(sys.ps2) if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = False command = self.GetTextRange(startpos, endpos) lines = command.split(os.linesep + ps2) lines = [ line.rstrip() for line in lines ] command = '\n'.join(lines) if self.reader.isreading: self.reader.input = command self.write(os.linesep) else: self.push(command) wx.FutureCall(1, self.EnsureCaretVisible) elif self.getCommand(rstrip = False): command = self.getMultilineCommand() self.clearCommand() self.write(command) else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip = True): ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) text = self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size] == ps2 and line > 0: line -= 1 self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size] == ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line += 1 self.GotoLine(line) stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep + ps2, '\n') command = command.rstrip() command = command.replace('\n', os.linesep + ps2) else: command = '' if rstrip: command = command.rstrip() return command def getCommand(self, text = None, rstrip = True): if not text: text = self.GetCurLine()[0] command = self.lstripPrompt(text) if command == text: command = '' if rstrip: command = command.rstrip() return command def lstripPrompt(self, text): ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) if text[:ps1size] == ps1: text = text[ps1size:] elif text[:ps2size] == ps2: text = text[ps2size:] return text def push(self, command, silent = False): if not silent: self.write(os.linesep) busy = wx.BusyCursor() self.waiting = True self.more = self.interp.push(command) self.waiting = False del busy if not self.more: self.addHistory(command.rstrip()) if not silent: self.prompt() def addHistory(self, command): self.historyIndex = -1 if command != '': if len(self.history) == 0 or command != self.history[0]: self.history.insert(0, command) dispatcher.send(signal = 'Shell.addHistory', command = command) def write(self, text): text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): lines = text.split('\r\n') for l in range(len(lines)): chunks = lines[l].split('\r') for c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\n')) lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines) return text def prompt(self): isreading = self.reader.isreading skip = False if isreading: prompt = str(sys.ps3) elif self.more: prompt = str(sys.ps2) else: prompt = str(sys.ps1) pos = self.GetCurLine()[1] if pos > 0: if isreading: skip = True else: self.write(os.linesep) if not self.more: self.promptPosStart = self.GetCurrentPos() if not skip: self.write(prompt) if not self.more: self.promptPosEnd = self.GetCurrentPos() self.EmptyUndoBuffer() if self.more: self.write(' ') self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): input = '' reader = self.reader reader.isreading = True self.prompt() try: while not reader.input: wx.YieldIfNeeded() input = reader.input finally: reader.input = '' reader.isreading = False input = str(input) return input def readlines(self): lines = [] while lines[-1:] != [ '\n']: lines.append(self.readline()) return lines def raw_input(self, prompt = ''): if prompt: self.write(prompt) return self.readline() def ask(self, prompt = 'Please enter your response:'): dialog = wx.TextEntryDialog(None, prompt, 'Input Dialog (Raw)', '') try: if dialog.ShowModal() == wx.ID_OK: text = dialog.GetValue() return text finally: dialog.Destroy() return '' def pause(self): self.ask('Press enter to continue:') def clear(self): self.ClearAll() def run(self, command, prompt = True, verbose = True): endpos = self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if prompt: self.prompt() if verbose: self.write(command) self.push(command) def runfile(self, filename): file = open(filename) try: self.prompt() for command in file.readlines(): if command[:6] == 'shell.': self.run(command, prompt = False, verbose = False) continue self.run(command, prompt = False, verbose = True) finally: file.close() def autoCompleteShow(self, command, offset = 0): self.AutoCompSetAutoHide(self.autoCompleteAutoHide) self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) list = self.interp.getAutoCompleteList(command, includeMagic = self.autoCompleteIncludeMagic, includeSingle = self.autoCompleteIncludeSingle, includeDouble = self.autoCompleteIncludeDouble) if list: options = ' '.join(list) self.AutoCompShow(offset, options) def autoCallTipShow(self, command, insertcalltip = True, forceCallTip = False): if self.CallTipActive(): self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command) if tip: dispatcher.send(signal = 'Shell.calltip', sender = self, calltip = tip) if not (self.autoCallTip) and not forceCallTip: return None if argspec and insertcalltip and self.callTipInsert: startpos = self.GetCurrentPos() self.write(argspec + ')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos = self.GetCurrentPos() tippos = curpos - (len(name) + 1) fallback = curpos - self.GetColumn(curpos) tippos = max(tippos, fallback) self.CallTipShow(tippos, tip) def OnCallTipAutoCompleteManually(self, shiftDown): if self.AutoCompActive(): self.AutoCompCancel() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd cpos = currpos pointavailpos = -1 while cpos >= stoppos: if self.GetCharAt(cpos) == ord('.'): pointavailpos = cpos break cpos -= 1 if pointavailpos != -1: textbehind = self.GetTextRange(pointavailpos + 1, currpos) pointavailpos += 1 if not shiftDown: stoppos = self.promptPosEnd textbefore = self.GetTextRange(stoppos, pointavailpos) self.autoCompleteShow(textbefore, len(textbehind)) else: cpos = pointavailpos begpos = -1 while cpos > stoppos: if chr(self.GetCharAt(cpos)).isspace(): begpos = cpos break cpos -= 1 if begpos == -1: begpos = cpos ctips = self.GetTextRange(begpos, currpos) ctindex = ctips.find('(') if ctindex != -1 and not self.CallTipActive(): if self.GetCharAt(currpos - 1) == ord('('): pass self.autoCallTipShow(ctips[:ctindex + 1], self.GetCurrentPos() == self.GetTextLength(), True) def writeOut(self, text): self.write(text) def writeErr(self, text): self.write(text) def redirectStdin(self, redirect = True): if redirect: sys.stdin = self.reader else: sys.stdin = self.stdin def redirectStdout(self, redirect = True): if redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def redirectStderr(self, redirect = True): if redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def CanCut(self): if self.GetSelectionStart() != self.GetSelectionEnd() and self.GetSelectionStart() >= self.promptPosEnd and self.GetSelectionEnd() >= self.promptPosEnd: return True else: return False def CanPaste(self): if self.CanEdit() and editwindow.EditWindow.CanPaste(self): return True else: return False def CanEdit(self): if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd and self.GetSelectionEnd() >= self.promptPosEnd: return True else: return False else: return self.GetCurrentPos() >= self.promptPosEnd def Cut(self): if self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): if self.CanCopy(): ps1 = str(sys.ps1) ps2 = str(sys.ps2) command = self.GetSelectedText() command = command.replace(os.linesep + ps2, os.linesep) command = command.replace(os.linesep + ps1, os.linesep) command = self.lstripPrompt(text = command) data = wx.TextDataObject(command) self._clip(data) def CopyWithPrompts(self): if self.CanCopy(): command = self.GetSelectedText() data = wx.TextDataObject(command) self._clip(data) def CopyWithPromptsPrefixed(self): if self.CanCopy(): command = self.GetSelectedText() spaces = ' ' command = spaces + command.replace(os.linesep, os.linesep + spaces) data = wx.TextDataObject(command) self._clip(data) def _clip(self, data): if wx.TheClipboard.Open(): wx.TheClipboard.UsePrimarySelection(False) wx.TheClipboard.SetData(data) wx.TheClipboard.Flush() wx.TheClipboard.Close() def Paste(self): if self.CanPaste() and wx.TheClipboard.Open(): ps2 = str(sys.ps2) if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)): data = wx.TextDataObject() if wx.TheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command = command.rstrip() command = self.fixLineEndings(command) command = self.lstripPrompt(text = command) command = command.replace(os.linesep + ps2, '\n') command = command.replace(os.linesep, '\n') command = command.replace('\n', os.linesep + ps2) self.write(command) wx.TheClipboard.Close() def PasteAndRun(self): text = '' if wx.TheClipboard.Open(): if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)): data = wx.TextDataObject() if wx.TheClipboard.GetData(data): text = data.GetText() wx.TheClipboard.Close() if text: self.Execute(text) def Execute(self, text): ps1 = str(sys.ps1) ps2 = str(sys.ps2) endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = text.lstrip() text = self.fixLineEndings(text) text = self.lstripPrompt(text) text = text.replace(os.linesep + ps1, '\n') text = text.replace(os.linesep + ps2, '\n') text = text.replace(os.linesep, '\n') lines = text.split('\n') commands = [] command = '' for line in lines: if line.strip() == ps2.strip(): line = '' lstrip = line.lstrip() if line.strip() != '' and lstrip == line and lstrip[:4] not in ('else', 'elif') and lstrip[:6] != 'except': if command: commands.append(command) command = line continue command += '\n' command += line commands.append(command) for command in commands: command = command.replace('\n', os.linesep + ps2) self.write(command) self.processLine() def wrap(self, wrap = True): try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is not available in this version.' def zoom(self, points = 0): self.SetZoom(points) def LoadSettings(self, config): self.autoComplete = config.ReadBool('Options/AutoComplete', True) self.autoCompleteIncludeMagic = config.ReadBool('Options/AutoCompleteIncludeMagic', True) self.autoCompleteIncludeSingle = config.ReadBool('Options/AutoCompleteIncludeSingle', True) self.autoCompleteIncludeDouble = config.ReadBool('Options/AutoCompleteIncludeDouble', True) self.autoCallTip = config.ReadBool('Options/AutoCallTip', True) self.callTipInsert = config.ReadBool('Options/CallTipInsert', True) self.SetWrapMode(config.ReadBool('View/WrapMode', True)) useAA = config.ReadBool('Options/UseAntiAliasing', self.GetUseAntiAliasing()) self.SetUseAntiAliasing(useAA) self.lineNumbers = config.ReadBool('View/ShowLineNumbers', True) self.setDisplayLineNumbers(self.lineNumbers) zoom = config.ReadInt('View/Zoom/Shell', -99) if zoom != -99: self.SetZoom(zoom) def SaveSettings(self, config): config.WriteBool('Options/AutoComplete', self.autoComplete) config.WriteBool('Options/AutoCompleteIncludeMagic', self.autoCompleteIncludeMagic) config.WriteBool('Options/AutoCompleteIncludeSingle', self.autoCompleteIncludeSingle) config.WriteBool('Options/AutoCompleteIncludeDouble', self.autoCompleteIncludeDouble) config.WriteBool('Options/AutoCallTip', self.autoCallTip) config.WriteBool('Options/CallTipInsert', self.callTipInsert) config.WriteBool('Options/UseAntiAliasing', self.GetUseAntiAliasing()) config.WriteBool('View/WrapMode', self.GetWrapMode()) config.WriteBool('View/ShowLineNumbers', self.lineNumbers) config.WriteInt('View/Zoom/Shell', self.GetZoom()) def GetContextMenu(self): menu = wx.Menu() menu.Append(wx.ID_UNDO, 'Undo') menu.Append(wx.ID_REDO, 'Redo') menu.AppendSeparator() menu.Append(wx.ID_CUT, 'Cut') menu.Append(wx.ID_COPY, 'Copy') menu.Append(frame.ID_COPY_PLUS, 'Copy Plus') menu.Append(wx.ID_PASTE, 'Paste') menu.Append(frame.ID_PASTE_PLUS, 'Paste Plus') menu.Append(wx.ID_CLEAR, 'Clear') menu.AppendSeparator() menu.Append(wx.ID_SELECTALL, 'Select All') return menu def OnContextMenu(self, evt): menu = self.GetContextMenu() self.PopupMenu(menu) def OnUpdateUI(self, evt): id = evt.Id if id in (wx.ID_CUT, wx.ID_CLEAR): evt.Enable(self.CanCut()) elif id in (wx.ID_COPY, frame.ID_COPY_PLUS): evt.Enable(self.CanCopy()) elif id in (wx.ID_PASTE, frame.ID_PASTE_PLUS): evt.Enable(self.CanPaste()) elif id == wx.ID_UNDO: evt.Enable(self.CanUndo()) elif id == wx.ID_REDO: evt.Enable(self.CanRedo())